package com.zjw.zy.heart.service.http;


import com.zjw.zy.heart.bean.weather.WeatherDaysResult;
import com.zjw.zy.heart.bean.weather.WeatherHoursResult;
import com.zjw.zy.heart.configuration.TaskPool;
import com.zjw.zy.heart.service.http.sources.IWeatherSourceService;
import com.zjw.zy.heart.service.http.factory.ConvertFactory;
import com.zjw.zy.heart.smi.JustWithIt;
import com.zjw.zy.heart.utils.LogUtils;
import lombok.NonNull;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

/**
 * @author ：zhong.jw
 * @date ：Created in 2022/9/27 16:03
 */
@Component()
public class HttpService {

    public static final String TAG = "HttpService";

    private final IWeatherSourceService sWeatherService = applyRetrofit(HttpConstant.WEATHER_BASE_URL).create(IWeatherSourceService.class);

    private static Retrofit applyRetrofit(String baseUrl) {
        return new Retrofit.Builder().baseUrl(baseUrl)
                .addConverterFactory(new ConvertFactory()).build();
    }

    //请求天气
    @Async(TaskPool.CONCURRENT_POOL)
    public void requestDaysWeather(@NonNull JustWithIt<WeatherDaysResult> observer, int days, long areaCode) {
        Call<WeatherDaysResult> weatherCall = sWeatherService.getWeather(AccessConstant.SPACE_KEY, "apikey",
                days, areaCode);

        weatherCall.enqueue(new Callback<>() {
            @Override
            public void onResponse(@NonNull Call<WeatherDaysResult> call, @NonNull Response<WeatherDaysResult> response) {
                observer.onWith(response.body());
            }

            @Override
            public void onFailure(@NonNull Call<WeatherDaysResult> call, @NonNull Throwable t) {
                LogUtils.e(TAG, "requestWeather onFailure");
                observer.onWith(null);
            }

        });
    }


    //请求天气
    @Async(TaskPool.CONCURRENT_POOL)
    public void requestHourlyWeather(@NonNull JustWithIt<WeatherHoursResult> observer, int hours, long areaCode) {

        Call<WeatherHoursResult> weatherCall = sWeatherService.getHourWeather(AccessConstant.SPACE_KEY, "apikey", hours, areaCode);

        weatherCall.enqueue(new Callback<>() {
            @Override
            public void onResponse(@NonNull Call<WeatherHoursResult> call, @NonNull Response<WeatherHoursResult> response) {
                observer.onWith(response.body());
            }

            @Override
            public void onFailure(@NonNull Call<WeatherHoursResult> call, @NonNull Throwable t) {
                LogUtils.e(TAG, "requestWeather onFailure");
                observer.onWith(null);
            }

        });
    }
}
